/*
www.thomasmueller.ch

Copyright (C) 2004 Thomas Mueller

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

*/
package ch.thomasmueller.saltyfiles.transformer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;


/**
 * Creates, appends and removes a random generated byte array called <b>Salt</b>.
 *
 * @author Thomas Mueller
 */
public class Salt
{
	public static final int SALT_LENGTH = 8;
	
	static private Logger log = LogManager.getLogger(Salt.class.getName());
	
	
	/**
	 * Creates the byte array using <code>SecureRandom</code>.
	 * @return the randomly generated byte array.
	 */
	public static byte[] createRandom()
	{			
		byte[] bytes = new byte[8];
		
		try
		{

			SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
			sr.nextBytes(bytes);
			
		} catch (NoSuchAlgorithmException e)
		{
			log.fatal(e.toString());
		}
		return bytes;
	}
	
	/**
	 * Appends a byte array to a file
	 * @param file to append the byte array
	 * @param salt to be appended
	 */
	public static void appendSalt(File file, byte[] salt)
	{
		
		log.debug(salt);

		try
		{
			
			FileOutputStream fos = new FileOutputStream(file, true);
			fos.write(salt);
			fos.flush();
			fos.close();

		} catch (FileNotFoundException e)
		{
			log.fatal(e);
		} catch (IOException e)
		{
			log.fatal(e);
		}
	}

	/**
	 * Read the byte array (length = {@link SALT_LENGTH}) form the file. 
	 * @param file to remve the salt from
	 * @return salt
	 */
	public static byte[] readSalt(File file)
	{
		RandomAccessFile raf;
		byte[] salt = new byte[SALT_LENGTH];

		try
		{
			raf = new RandomAccessFile(file, "rw");

			raf.seek(raf.length() - (SALT_LENGTH));
			raf.read(salt);
			raf.setLength(raf.length() - SALT_LENGTH);
			raf.close();
		} catch (FileNotFoundException e)
		{
			log.fatal(e);
			e.printStackTrace();
		} catch (IOException e)
		{
			log.fatal(e);
		}
		return salt;
	}
}
